package com.project.controller;

import com.project.bean.UserBean;
import com.project.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private IUserService service;

    @RequestMapping("login")
    public String login(String name, String pwd, HttpServletRequest req) {
        UserBean user = service.login(name, pwd);
        if (user != null) {
            req.getSession().setAttribute("loginUser", user);
            return "ok";
        }
        return "no";
    }

    @RequestMapping("add")
    public String add(UserBean user) {
        service.add(user);
        return "ok";
    }

    @RequestMapping("out")
    public String signOut(HttpServletRequest req){
        UserBean userBean = (UserBean) req.getSession().getAttribute("loginUser");
        if (userBean == null){
            return "noUser";
        }
        req.getSession().setAttribute("loginUser",null);
        return "ok";
    }

    @RequestMapping("findById")
    public UserBean findById(HttpServletRequest req){
        UserBean user = (UserBean) req.getSession().getAttribute("loginUser");
        return service.findById(user.getId());
    }

    @RequestMapping("findByName")
    public String findByName(String name){
        UserBean user = service.finByName(name);
        if (user == null){
            return "ok";
        }
        return "no";
    }

}
